JavaScript Memory Management

Visualizing `WeakRef` and `FinalizationRegistry` for advanced memory control.

WeakRef

A `WeakRef` (Weak Reference) object allows you to hold a weak reference to another object. Unlike a normal reference, a weak reference does not prevent the object it points to from being garbage-collected. This is useful for building caches or mappings of objects without causing memory leaks.

let obj = { data: 'some data' };
const weakRef = new WeakRef(obj);
obj = null; // The object is now a candidate for garbage collection.
const objFromWeakRef = weakRef.deref(); // Will return undefined if GC'd.

A `WeakRef` is a "take a look, but don't hold on" kind of relationship. The Garbage Collector can clean up the object at any time, even if a `WeakRef` still exists.

Strong Reference:
{ name: 'data' }

WeakRef:
weakRef.deref()

Status: Object exists.


FinalizationRegistry

A `FinalizationRegistry` allows you to register objects and a cleanup callback function. The callback is executed after a registered object has been garbage-collected. This provides a way to perform cleanup tasks when an object's memory is reclaimed.

const registry = new FinalizationRegistry(value => {
  console.log(`Object with value ${value} was garbage-collected.`);
});
let obj = { data: 'cleanup task' };
registry.register(obj, 'cleanup task value');
obj = null; // Object becomes eligible for GC, triggering the callback later.

A `FinalizationRegistry` is a diligent janitor. When an object is thrown away (garbage-collected), the janitor performs a final cleanup task.

Object to Watch:
{ name: 'file' }

FinalizationRegistry:
// Registers cleanup callback

Callback Status: Waiting...